import React from 'react'
import "./index.less"

import {connect} from "react-redux"
import action from '../../../../store/action/ymz';

import {getData} from "../../../../api"
import request from "../../../../utils/request"

// 引入封装的WebSocket
import {socket} from '../../../../utils/websocket'

// vant组件
import { Loading, NavBar, Cell } from 'react-vant';


import newTouch from "../../../../utils/touch"
const NewFriend = (props) => {
    // 本地存储信息
    const local = JSON.parse(localStorage.getItem('token'))
    // 总数据
    const [data,setData] = React.useState ([])


    // 筛选后的数据
    const [filterData, setFilterData] = React.useState([])
    
    const filterDataFriend = async () => {
        let newData= await getData()
        setData(newData)
        // newData.infos.forEach(current => {
            
        // })
        let newArr = newData.friendData.map(item => {
            if (item.fromId === local.info_id || item.toId === local.info_id) {
                // item.fromId === local.info_id&& current.info_id === item.toId || item.toId === local.info_id && current.info_id === item.fromId
                let current = newData.infos.find(ite => {
                    return item.fromId === local.info_id&& ite.info_id === item.toId || item.toId === local.info_id && ite.info_id === item.fromId
                })
                let obje = {
                    createtimes: item.createtimes,
                    fromId: item.fromId,
                    id: item.id,
                    img: item.img,
                    isBlacklist: item.isBlacklist,
                    isOnlyChat: item.isOnlyChat,
                    msg: item.msg,
                    remark: item.remark,
                    state: item.state,
                    time: item.time,
                    toId: item.toId,
                    uuid: item.uuid,
                    QRCode: current.QRCode,
                    account: current.account,
                    collect: current.collect,
                    friendCircle: current.friendCircle,
                    headPortrait: current.headPortrait,
                    id: current.id,
                    info_id: current.info_id,
                    name: current.name,
                    pass: current.pass,
                    phoneNum: current.phoneNum,
                    sex: current.sex,
                    signature: current.signature,
                    site: current.site,
                    localName:item.localName,
                    isRender:item.isRender
                }
                let newDay = new Date().getDate()
                let newMonth = new Date().getMonth()+1
                let newDayly = new Date(obje.createtimes).getDate()
                let newMonthly = new Date(obje.createtimes).getMonth()+1
                obje.time = {
                    day:newDay - newDayly,
                    newMonth,
                    newMonthly
                }
                return obje;
            }
        }).filter(item => {
            if(item !== undefined && item.isRender){
                return item
            }
        })
        if (newArr.length === 0) {
            return false
        }
        console.log(newArr);
        setFilterData(newArr);
    }
    React.useEffect(async () => {
        // webSocket
        socket.fromId = `?user=${local.info_id}`
        socket.init()
        socket.websock.onmessage = async function (messages) {
            let message = JSON.parse(messages.data)
            console.log(message, 'newFriend  135');

            filterDataFriend()
        }

        filterDataFriend()
    }, [])
    
    // 返回
    const back = () => {
        setLoading(true)
        setTimeout(() => {
            setLoading(false)
            props.history.push(props.location.state.path)
        }, 1000)
    }
    // 控制加载组件的变量
    const [showLoading, setLoading] = React.useState(false);

    // 添加朋友
    const addFriend = () => {
        props.history.push({
            pathname: "/main/addFriend",
            state: { path: props.location.pathname, oldPath: props.location.state.path }
        })
    }
    // 同意
    const agree = (item,e) => {
        e.stopPropagation()
        item.state = 0
        item.toId = item.fromId
        item.fromId = local.info_id
        request.post("/ymz/addInfoData",{obj:item}).then(res => {
            filterDataFriend();
            socket.send({ to_id: res.data.newData.toId, msg: res.data.newData })
        })
        setShowButton(false);//隐藏到按钮
        setShowText('已添加')
    }
    // 拒绝
    const reject = (item,e) => {
        e.stopPropagation()
        item.state = 1
        item.toId = item.fromId
        item.fromId = local.info_id
        request.post("/ymz/addInfoData",{obj:item}).then(res => {
            filterDataFriend();
            socket.send({ to_id: res.data.newData.toId, msg: res.data.newData })
        })
        setShowButton(false);//隐藏到按钮
        setShowText('已拒绝')
    }

    // 跳转到好友详情页
    const toFriendDetail = (res) => {
        let obj = data.infos.find(item => {
            return item.info_id === res.info_id
        })
        console.log(props);
        props.history.push({
            pathname:"/main/friendDetail",
            state:{
                msg:obj,
                path:props.location.pathname,
                oldPath: props.location.state.path,
            }
        })
    }
    // 跳转到搜索页
    const toSearch = () => {
        props.history.push({
            pathname:"/main/addFriendSearchPage",
            state:{
                path:props.location.pathname,
                oldPath:props.location.state.path,
            }
        })
    }

    // 控制是否显示按钮（同意和拒绝）
    const [showButton, setShowButton] = React.useState(true)
    const [showText, setShowText] = React.useState()


    const mainRef = React.useRef()
    return (
        <div className='NewFriend'>
            <header>
                <NavBar
                    title="新的朋友"
                    style={{ backgroundColor: "#ededed" }}
                    leftArrow
                    rightText={
                        <span>
                            添加朋友
                        </span>
                    }
                    onClickLeft={back}
                    onClickRight={addFriend}
                />
            </header>
            <main ref={mainRef} onTouchStart={(e) => {newTouch.touchStart(e)}} onTouchMove={(e) => {newTouch.touchMove(e,mainRef)}} onTouchEnd={(e) => {newTouch.touchEnd(e,mainRef)}}>
                {/* 搜索框 */}
                <div className='search'>
                    <p onClick={toSearch}>
                        <svg className='icon' aria-hidden="true">
                            <use xlinkHref='#icon-sousuo1'></use>
                        </svg>
                        <span>微信号/手机号</span>
                    </p>
                </div>
                {/* 添加手机联系人 */}
                <div className='addLinkmanContacts'>
                    <Cell title="添加手机联系人" isLink icon="phone" />
                </div>
                {/* 添加好友列表 */}
                <div className='addFriendList'>
                    <p className='oldTime'>近三天</p>
                    <ul>
                        {
                            filterData.map((item, index) => {
                                {
                                    return item.time.newMonthly==item.time.newMonth && item.time.day<=3 ? <li key={index} onClick={() => {
                                        toFriendDetail(item)
                                    }}>
                                        <p>
                                            <img src={item.img} alt="" />
                                        </p>
                                        <div>
                                            <p>
                                                <span>{item.info_id === local.info_id?item.localName:item.name}</span>
                                                <span>{item.info_id !== local.info_id?item.msg:item.remark}</span>
                                            </p>
                                            {
                                                local.info_id === item.toId&&item.state==='2'?<p>
                                                    {showText}
                                                    {showButton ? <button onClick={(e) => {agree(item,e)}}>同意</button> : null}
                                                    {showButton ? <button onClick={(e) => {reject(item,e)}}>拒绝</button> : null}
                                                </p>:(item.state == 2?'等待验证':(item.state == 1?'已拒绝':item.state == 0?'已添加':null))
                                            }
                                        </div>
                                    </li> : null
                                }
                            })
                        }
                    </ul>
                    <p className='oldTime'>三天前</p>
                    <ul>
                        {
                            filterData.map((item, index) => {
                                {
                                    return item.time.newMonthly!=item.time.newMonth || item.time.day>3? <li key={index}>
                                        <p>
                                            <img src={item.img} alt="" />
                                        </p>
                                        <div>
                                            <p>
                                                <span>{item.name||item.remark}</span>
                                                <span>{item.msg}</span>
                                            </p>
                                            {   
                                                item.time.newMonthly>item.time.newMonth?'已过期':item.state == 2?'等待验证':(item.state == 1?'已拒绝':item.state == 0?'已添加':'')
                                            }
                                        </div>
                                    </li> : null
                                }
                            })
                        }
                    </ul>
                </div>
            </main>
            {/* 加载中动画 */}
            {showLoading ? <Loading vertical type="spinner" /> : null}
        </div>
    )
}
export default connect(state=>state.ymz,action)(NewFriend)